<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>全选案例</title>
</head>

<body>
    <div>
        <span>你爱好的运动是?</span>
        <input type="checkbox" name="checkall" id="checkall">全选/全不选
    </div>
    <div>
        <input type="checkbox" name="sports" id="football" value="足球">足球
        <input type="checkbox" name="sports" id="basketball" value="篮球">篮球
        <input type="checkbox" name="sports" id="badminton" value="羽毛球">羽毛球
        <input type="checkbox" name="sports" id="table-tennis" value="乒乓球">乒乓球
    </div>
    <div>
        <button id="all">全选</button>
        <button id="unall">全不选</button>
        <button id="inverse">反选</button>
        <button id="submit">提交</button>
    </div>
</body>
<script>
    var checkbox = document.getElementsByName('sports');
    var checkAll = document.getElementById('checkall');
    var all = document.getElementById('all');
    var unall = document.getElementById('unall');
    var inverse = document.getElementById('inverse');
    var submit = document.getElementById('submit');
    // console.log(checkAll);
    // console.log(checkbox);
    function allcheck() {
        for (var i = 0; i < checkbox.length; i++) {
            // console.log(i);
            checkbox[i].checked = true;
        }
    }

    function unallcheck() {
        for (var i = 0; i < checkbox.length; i++) {
            // console.log(i);
            checkbox[i].checked = false;
        }
    }

    function fan() {
        for (var i = 0; i < checkbox.length; i++) {
            if (checkbox[i].checked) {
                checkbox[i].checked = false;
            } else {
                checkbox[i].checked = true;
            }
        }
    }
    all.onclick = function () {
        allcheck();
    }
    unall.onclick = function () {
        unallcheck();
    }
    inverse.onclick = function () {
        fan();
    }
    checkAll.onclick = function () {
        if (checkAll.checked == true) {
            allcheck();
        } else {
            unallcheck();
        }
    }
    submit.onclick = function () {
        var hobby = "";
        for (i = 0; i < checkbox.length; i++) {
            if (checkbox[i].checked == true) {
                // alert('你爱好的运动是' + checkbox[i].value)
                hobby = hobby + checkbox[i].value + ',';
            }
        }
        alert('你爱好的运动是' + hobby);
    }
</script>

</html>